@model  AdminQueryViewModel
@using OrchardCore.ContentManagement;
@inject IContentManager ContentManager

@{
    var matchAllQuery = Convert.ToBase64String(System.Text.Encoding.
        UTF8.GetBytes(
            @"var query=freeSql.Select<ContentItemIndex>().Where(x => x.Published).Take(10);
var result=  new FreeSqlQueryResults
            {
                TotalCount = query.Count(),
                Items = query.ToList(x=>Id)
            };
return result;"));
}

<style asp-name="codemirror"></style>
<script asp-name="codemirror" depends-on="admin" at="Foot"></script>
<script asp-name="codemirror-mode-javascript" at="Foot"></script>
<script asp-name="codemirror-mode-sql" at="Foot"></script>
<script asp-name="monaco" depends-on="admin" at="Foot"></script>

<zone Name="Title"><h1>@RenderTitleSegments(T["FreeSQL Query"])</h1></zone>

<div asp-validation-summary="All"></div>

<form asp-action="Query" method="post" class="no-multisubmit">
    <div class="row">
        <div class="col-md-6">

            <div class="mb-3">
                <label asp-for="DecodedQuery"> @T["Template"]</label>
                <div id="@Html.IdFor(x => x.DecodedQuery)_editor" asp-for="Text" style="min-height: 400px;" class="form-control" ></div>
                <textarea asp-for="DecodedQuery" hidden>@Html.Raw(Model.DecodedQuery)</textarea>
                <span class="hint">@T["You can <a href=\"{0}\">click here</a> to query all content items.", Html.Raw(Url.Action("Query", "Admin", new { area = "EasyOC.OrchardCore.FreeSql", Query = matchAllQuery }))]</span>
                <span class="hint">@T["The SQL query uses standard SQL92 syntax and is converted based on the actual database. Tables will be prefixed automatically."]</span>

            </div>
        </div>
        <div class="col-md-6">

            <div class="mb-3">
                <label asp-for="Parameters">@T["Parameters"]</label>
                <textarea asp-for="Parameters" rows="1" class="form-control"></textarea>
                <span class="hint">@T["An optional Json object containing the parameter values for this query."]</span>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6">
            <div class="mb-3">
                <button type="submit" class="btn btn-primary">@T["Query"]</button>
            </div>
        </div>
    </div>
</form>
@if (Model.Elapsed != TimeSpan.Zero)
{
    <div class="row">
        <div class="col-md-6">
            <div class="mb-3">
                <label asp-for="RawSql">@T["Final SQL Query"]</label>
                <textarea asp-for="RawSql" rows="12" class="form-control"></textarea>
                <span class="hint">@T["The query as it will be executed by the SQL database."]</span>
            </div>

            <div class="mb-3">
                <a href="@Url.Action("Create", "Admin", new { area = "EasyOC.OrchardCore.FreeSql", id = "FreeSql", query = Model.DecodedQuery })" class="btn btn-success">@T["Create"]</a>
            </div>
        </div>
    </div>
}

@if (Model.Documents.Any())
{
    <span class="text-muted">@T["Query executed in {0} ms", Model.Elapsed.TotalMilliseconds]</span>

    var json = "";
    if (Model.Documents.Any())
    {
        json = "[";
        var i = 0;

        @foreach (var document in Model.Documents)
        {
            json += Json.Serialize(document);
            if (i < Model.Documents.Count() - 1)
            {
                json += ",";
            }
            i++;
        }

        json += "]";
    }

    <div class="form-control" style="min-height: 400px;">
        <div id="monaco_editor" style="min-height: 385px;" dir="@Orchard.CultureDir()"></div>
    </div>
    <textarea id="monaco_textarea" hidden>@json</textarea>
}

@{
    string sqlmode = "text/x-sql";

    if (Model.FactoryName.Contains("Sqlite"))
    {
        sqlmode = "text/x-sqlite";
    }
    else if (Model.FactoryName.Contains("Mysql"))
    {
        sqlmode = "text/x-mysql";
    }
    else if (Model.FactoryName.Contains("Npgsql"))
    {
        sqlmode = "text/x-pgsql";
    }
    else if (Model.FactoryName.Contains("Sql"))
    {
        sqlmode = "text/x-mssql";
    }
}

<script at="Foot">
    // $(function () {
    //     CodeMirror.fromTextArea(document.getElementById('@Html.IdFor(m => m.DecodedQuery)'), { mode: "text/x-pgsql", lineNumbers: true, viewportMargin: Infinity });
    //     CodeMirror.fromTextArea(document.getElementById('@Html.IdFor(m => m.Parameters)'), { mode: "javascript", json: true, lineNumbers: true, viewportMargin: Infinity });
    //     if (rawSql = document.getElementById('@Html.IdFor(m => m.RawSql)')) {
    //       CodeMirror.fromTextArea(rawSql, { mode: "@sqlmode", lineNumbers: true, readonly: true, viewportMargin: Infinity });
    //     }
    // });
        // $(function () {
        //     CodeMirror.fromTextArea(document.getElementById('@Html.IdFor(m => m.DecodedQuery)'), { mode: "text/x-pgsql", lineNumbers: true, viewportMargin: Infinity });
        //     CodeMirror.fromTextArea(document.getElementById('@Html.IdFor(m => m.Parameters)'), { mode: "javascript", json: true, lineNumbers: true, viewportMargin: Infinity });
        //     if (rawSql = document.getElementById('@Html.IdFor(m => m.RawSql)')) {
        //       CodeMirror.fromTextArea(rawSql, { mode: "@sqlmode", lineNumbers: true, readonly: true, viewportMargin: Infinity });
        //     }
        // });


</script>
<script asp-name="monaco" depends-on="admin" at="Foot"></script>
<script at="Foot" asp-name="jsonrecipe-editor" depends-on="monaco, admin">
    $(document).ready(function () {
        require(['vs/editor/editor.main'], function () {

            const html = document.getElementsByTagName("html")[0];
            const mutationObserver = new MutationObserver(setTheme);
            mutationObserver.observe(html, { attributes: true });

            function setTheme() {
                var theme = html.dataset.theme;
                if (theme === "darkmode") {
                    monaco.editor.setTheme('vs-dark')
                } else {
                    monaco.editor.setTheme('vs')
                }
            }
            setTheme();
            createEditor('@Html.IdFor(x => x.DecodedQuery)_editor',
                         '@Html.IdFor(x => x.DecodedQuery)',
                         "csharp");
            createEditor("monaco_editor",@Html.IdFor(m => m.Parameters),"json");
            createEditor("monaco_editor","monaco_textarea","json");

        });
    });
    function createEditor(editorId,textAreaId,language) {
        const textArea = document.getElementById(textAreaId);
        if (!textArea) { return; }
        const editorWapper=document.getElementById(editorId);
        if (!editorWapper) {  return; }
        const modelUri = monaco.Uri.parse("json://grid/settings.json");
        const jsonModel = monaco.editor.createModel(JSON.stringify(textArea, null, 4),"json", modelUri);

        var editor = monaco.editor.create(editorWapper, {
            automaticLayout: true,
            language: language,
            lineNumbers: true,
            minimap: { enabled: false },
            model: jsonModel
        });

        editor.getModel().setValue(textArea.value);

        //format json
        setTimeout(function() {
            editor.getAction('editor.action.formatDocument').run();
        }, 300);

        window.addEventListener("submit", function () {
            textArea.value = editor.getValue();
        });
    }
</script>
